﻿using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace NotificationLib
{
    public class PushoverNotification : Notification
    {

 
        PushoverNotificationConfig Config { get; set; }
        public string UserKey { get; set; }


        public PushoverNotification()
        {

        }

        public PushoverNotification(PushoverNotificationConfig config, string userKey, string title, string message )
        {
            Config = config;
            Title = title;
            Message = message;
            UserKey = userKey;
        }

        public override bool Send()
        {

            string pri = ((short)Config.Priority).ToString();

            var parameters = new NameValueCollection 
            {
                { "token", Config.ApiKey },
                { "user", UserKey },
                { "message", Message },
                { "title", Title },
                { "priority", pri  }
                    
            };


            if (Config.Device != null)
                parameters.Add("device", Config.Device);

            if (Config.Sound != null)
                parameters.Add("sound", Config.Sound);

                using (var client = new WebClient())
                {
                    try
                    {

                        client.UploadValues("https://api.pushover.net/1/messages.json", parameters);
                        
                        
                    }
                    catch(WebException we)
                    {

                        var response = we.Response as HttpWebResponse;

                        if (response != null)
                        {
                            int code = (int)response.StatusCode;

                            //if the code is a 4xx code return true to remove from queue. Should not be an exception for a 200 but included.
                            if (code == 200 || (code >= 400 && code < 500))
                            {
                                return true; 
                            }
                            else
                            {
                                return false; //any other codes we are allowed to retry.
                            }
                        }
                        
                    }
                    return true;   
                    
                }

               

        }


       
    }
}
